package com.ming.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ming.dao.BookCategoryRepository;
import com.ming.domain.BookCategory;
import com.ming.service.BookCategoryService;

@Service
public class BookCategoryServiceImpl implements BookCategoryService {

    @Autowired
    private BookCategoryRepository bookCategoryRepository;

    @Override
    public Optional<BookCategory> findOne(Integer id) {
        return bookCategoryRepository.findById(id);
    }

    @Override
    public List<BookCategory> findAll() {
        return bookCategoryRepository.findAll();
    }

    @Override
    public List<BookCategory> findByDate(LocalDate date) {
        
        Specification<BookCategory> spec = new Specification<BookCategory>() {

            @Override
            public Predicate toPredicate(Root<BookCategory> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                // 1        
                List<Predicate> predicates = new ArrayList<>();
                LocalDateTime startDateTime = date.atStartOfDay();
                LocalDateTime endDateTime = date.plusDays(1).atStartOfDay();

                Predicate predicate1 = criteriaBuilder.between(root.get(BookCategory._CREATED_TIME), startDateTime, endDateTime);
                // 2
                Predicate predicate2 = criteriaBuilder.equal(root.get(BookCategory._BOOK_CATEGORY_NAME), "java");
                
                predicates.add(predicate1);
                predicates.add(predicate2);

                return criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()]));
            
                        
            }
            
        };

        return bookCategoryRepository.findAll(spec);
    }
}
